﻿using AutoMapper;
using MediatR;
using SmartCity.ProcessEngine.Api.Write.Application.Command.Form;
using SmartCity.ProcessEngine.Domain.Entities;
using SmartCity.ProcessEngine.ErrorCode;
using SmartCity.ProcessEngine.Infrastructure.Interface;
using Yitter.IdGenerator;

namespace SmartCity.ProcessEngine.Api.Write.Application.CommandHandler.Form
{
    public class DelFormHandler:IRequestHandler<DelFormCommand,ApiResult<int>>
    {
        private readonly IBaseRepository<FormModel> formRepo;
        private readonly IMapper mapper;
        private readonly ILogger<DelFormHandler> logger;

        /// <summary>
        /// 注入删除表单所需的仓储和映射组件
        /// </summary>
        /// <param name="formRepo"></param>
        /// <param name="mapper"></param>
        public DelFormHandler(IBaseRepository<FormModel> formRepo,IMapper mapper,ILogger<DelFormHandler> logger)
        {
            this.formRepo = formRepo;
            this.mapper = mapper;
            this.logger = logger;
        }

        public async Task<ApiResult<int>> Handle(DelFormCommand request, CancellationToken cancellationToken)
        {
            //根据id查找要删除的表单数据实体
            var entity =await formRepo.GetModel(request.Id);
            if (entity == null) {
                return new ApiResult<int>().Error("您要删除的表单不存在!");
            }
            entity.IsDeleted = true;//逻辑删除
             

            int r = await formRepo.UpdateAsync(entity);
            if (r > 0)
            {
                return new ApiResult<int>().Success("删除表单成功!", r);
            }
            else { 
                return new ApiResult<int>().Fail("删除表单失败!");

            }
        }
    }
}
